package com.he1618.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import feign.RequestTemplate;
import feign.Response;
import feign.codec.Decoder;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

@Configuration
public class FeignConfig {

    @Bean
    public Encoder feignEncoder() {
        return new AesEncoder();
    }

    @Bean
    public Decoder feignDecoder() {
        return new AesDecoder();
    }


    private static class AesEncoder implements Encoder {

        @Override
        public void encode(Object object, Type type, RequestTemplate requestTemplate) throws EncodeException {
            if (object != null) {
                // Convert your object to JSON, if needed
                String jsonContent = convertObjectToJson(object);

                // Perform AES encryption on the JSON content
                String encryptedContent = EncryptUtil.encrypt(jsonContent, "1234567891234567");

                // Set the encrypted content in the RequestTemplate
                requestTemplate.body(encryptedContent.getBytes(), StandardCharsets.UTF_8);
            }
        }
        private final ObjectMapper objectMapper = new ObjectMapper();

        private String convertObjectToJson(Object object) {
            try {
                return objectMapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Error converting object to JSON", e);
            }
        }



        // Implement the necessary methods...
    }

    private static class AesDecoder implements Decoder {

        private final ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public Object decode(Response response, Type type) throws IOException {
            // Perform AES decryption on the response body
            String encryptedContent = response.body().toString();
            String decryptedContent = EncryptUtil.decrypt(encryptedContent, "1234567891234567");
            return convertJsonToObject(decryptedContent, type);
        }
        private <T> T convertJsonToObject(String json,Type type) {
            try {
                JavaType javaType = TypeFactory.defaultInstance().constructType(type);
                return objectMapper.readValue(json, javaType);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Error converting JSON to object", e);
            }
        }
    }


}
